<?php

namespace app\admin\controller;

use think\Page;

use think\Db;



class Workorder extends Base{

    /**

     * 列表

     * @return mixed

     */

    public function index(){

        $keywords = input('keywords/s');
        $keywords1 = input('keywords1/s');
        $condition = [];
        $condition1 = [];
        if ($keywords){
            $condition['month'] = ['eq',datetime('Y-m-d H:m:s',strtotime($keywords))];
        }
         if ($keywords1){
             $condition1['model'] = array('LIKE', $keywords1.'%');
            //  var_dump($condition1);die();
        }

        // 多语言

        // $condition['lang'] = array('eq', $this->admin_lang);



        $adPositionM =  M('workorder');

        $count = $adPositionM->where($condition)->count();// 查询满足要求的总记录数

        $Page = new Page($count, config('paginate.list_rows'));// 实例化分页类 传入总记录数和每页显示的记录数

        $list = $adPositionM->where($condition)->where($condition1)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();



            foreach ($list as &$val){



            if ($val['img']){

                if(strpos($val['img'], ",") !== false){
                    $val['img_path_arr'] = explode(',', $val['img']);
                }else{
                    $val['img_path_arr'][0] = $val['img'];
                }

            }

            else{

                $val['img_path_arr'] = [];

            }



            // $val['supplier'] = $this->getUserGxsName($val['supplier_id']);
          

        }

        $show = $Page->show();// 分页显示输出

        $this->assign('page',$show);// 赋值分页输出

        $this->assign('list',$list);// 赋值数据集

        $this->assign('pager',$Page);// 赋值分页对象

        return $this->fetch();

    }


    /**

     * 新增

    */

    public function add()

    {

        //防止php超时

        function_exists('set_time_limit') && set_time_limit(0);

        $this->language_access(); // 多语言功能操作权限

        if (IS_POST) {

        $post = input('post.');
     
            $data = array(

                'submitter' => trim($post['submitter']),

                'model' => trim($post['model']),

                'category'       => trim($post['category']),
                
                'video' => trim($post['video']),

                'month' => trim($post['month']),
                
                'status'       => trim($post['status']),
                
                'handler' => trim($post['handler']),

                'createtime' => trim($post['createtime']),
                
            );
        $file = request()->file();//视频上传
        //将文件保存到public/uploads目录下面
        // $info = $file->validate(['size'=>1048576,'ext'=>'xls,xlsx'])->move( './uploads');
        if($file){
          $info = $file['file']->move('uploads/video'); //这里是重点
          $a=$info->getSaveName();
          $data['video'] = 'http://'.$_SERVER["HTTP_HOST"].'/uploads/video/'.$a;
            // if($info){
            //     // // 成功上传后 获取上传信息
            //     // // 输出 jpg
            //     // echo $info->getExtension();
            //     // echo '<br>';
            //     // // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
            //     // echo $info->getSaveName();
            //     // echo '<br>';
            //     // // 输出 42a79759f284b767dfcb2a0197904287.jpg
            //     // echo $info->getFilename();
            //     // echo '<br>';
            // }else{
            //     // 上传失败获取错误信息
            //     // echo $file->getError();
            // }
        }
        // print_r($info->getSaveName());die;


            // 添加广告位置表信息




            $skuImgArr = [];

            foreach ($post['img'] as $key => $value) {

                if (!empty($value)) {

                    array_push($skuImgArr, $value);

                }

            }

            $data['img']      = implode(',', $skuImgArr);



            $insertId = M('Workorder')->insertGetId($data);



            if ($insertId) {



                adminLog('新增采购：'.$post['title']);

                $this->success("操作成功", url('Workorder/index'));

            } else {

                $this->error("操作失败", url('Workorder/index'));

            }

            exit;

        }else{

            $data = $this->appearanceData();

            $this->assign('appearance', $data);
// $this->assign('info', $info);
            // $this->assign('slist', $this->getUserGxsList());

            return $this->fetch();

        }

    }





    /**

     * 编辑

     */

    public function edit()

    {

        if (IS_POST) {

            $post = input('post.');

            if(!empty($post['id'])){



                $data = array(

                    'submitter' => trim($post['submitter']),

                    'model' => trim($post['model']),

                    'category'       => trim($post['category']),

                    'video'       => trim($post['video']),

                    'img'       => strval(trim($post['img'])),

                   'month'       => strval(trim($post['month'])),


                );



                $skuImgArr = [];

                foreach ($post['img'] as $key => $value) {

                    if (!empty($value)) {

                        array_push($skuImgArr, $value);

                    }

                }

                $data['img']      = implode(',', $skuImgArr);

                $r = Db::name('workorder')->where('id', $post['id'])->update($data);

            }



            if ($r) {

                adminLog('编辑采购：'.$post['model']);

                $this->success("操作成功", url('Workorder/index'));

            } else {

                $this->error("操作失败");

            }

        }



        $assign_data = array();



        $id = input('id/d');

        $field = M('workorder')

            ->where(array('id'=>$id))

            ->find();

        if (empty($field)) {

            $this->error('采购记录不存在，请联系管理员！');

            exit;

        }

        $data = $this->appearanceData();

        $this->assign('appearance', $data);

        $assign_data['field'] = $field;

        $imgArr = explode(',', $field['img']);

        // $this->assign('slist', $this->getUserGxsList());

        $this->assign('imgArr', $imgArr);

        $this->assign($assign_data);

        return $this->fetch();

    }
    


    
    /**

     * 查看

     */

    public function see()

    {
        if (IS_POST) {

            $post = input('post.');

            if(!empty($post['id'])){

                $data = array(

                    'area' => trim($post['area']),

                    'supplier_id' => trim($post['supplier_id']),

                    'title'       => trim($post['title']),

                    'desc'       => trim($post['desc']),

                    'cate'       => strval(trim($post['cate'])),

                    'admin_id'    => session('admin_id'),

                    'lang'        => $this->admin_lang,

                    'size_logn'    => trim($post['size_logn']),

                    'update_time' => getTime(),

                    'sku'       => strval(trim($post['sku'])),

                    'size_width'       => strval(trim($post['size_width'])),

                    'size_height'       => strval(trim($post['size_height'])),

                    'pk_long'       => strval(trim($post['pk_long'])),

                    'pk_width'       => strval(trim($post['pk_width'])),

                    'pk_height'       => strval(trim($post['pk_height'])),

                    'weight'       => strval(trim($post['weight'])),

                    'price'       => strval(trim($post['price'])),

                    'freight'       => strval(trim($post['freight'])),

                    'material'      => strval(trim($post['material'])),

                    'is_sale'       => strval(trim($post['is_sale'])),

                    'is_ds_packge'       => strval(trim($post['is_ds_packge'])),

                    'is_stock'       => strval(trim($post['is_stock'])),

                    'fun_desc'       => strval(trim($post['fun_desc'])),

                    'appearance'       => strval(trim($post['appearance'])),

                    'is_install_pic'       => strval(trim($post['is_install_pic'])),

                    'delivery_method'       => strval(trim($post['delivery_method'])),

                    'df_method'       => strval(trim($post['df_method'])),

                    'settle_method'       => strval(trim($post['settle_method'])),

                    'is_lou'       => strval(trim($post['is_lou'])),

                    'is_clear_store'       => strval(trim($post['is_clear_store'])),

                    'img_method'       => strval(trim($post['img_method'])),

                    'is_yy_img'       => strval(trim($post['is_yy_img'])),

                );

                $skuImgArr = [];

                foreach ($post['img'] as $key => $value) {

                    if (!empty($value)) {

                        array_push($skuImgArr, $value);

                    }

                }

                $data['img']      = implode(',', $skuImgArr);

                $r = Db::name('workorder')->where('id', $post['id'])->update($data);

            }
            
            if ($r) {

                adminLog('编辑采购：'.$post['title']);

                $this->success("操作成功", url('Workorder/index'));

            } else {

                $this->error("操作失败");

            }

        }



        $assign_data = array();

        $id = input('id/d');

        $field = M('workorder')

            ->where(array('id'=>$id))

            ->find();

        if (empty($field)) {

            $this->error('采购记录不存在，请联系管理员！');
            exit;
        }

        $data = $this->appearanceData();

        $this->assign('appearance', $data);

        $assign_data['field'] = $field;

        $imgArr = explode(',', $field['img']);

        // $this->assign('slist', $this->getUserGxsList());

        $this->assign('imgArr', $imgArr);

        $this->assign($assign_data);

        return $this->fetch();

    }

    
    
    
    



    /**

     * 删除

     */

    public function del()

    {

        $this->language_access(); // 多语言功能操作权限



        $id_arr = input('del_id/a');

        $id_arr = eyIntval($id_arr);

        if(IS_POST && !empty($id_arr)){



            $r = M('workorder')->where('id','IN',$id_arr)->delete();

            if ($r) {



                adminLog('删除采购-id：'.implode(',', $id_arr));

                $this->success('删除成功');

            } else {

                $this->error('删除失败');

            }

        }else{

            $this->error('参数有误');

        }

    }



    /**

     * 纸箱外观

     * @param int $index

     * @return string|string[]

     */

    private function appearanceData($index = 0){

        $data = [

            1 => '合格，好',

            2 => '合格，不好',

            3 => '不合格，好',

            4 => '不合格，不好'

        ];

        return $index ? $data[$index] : $data;

    }



    private function checkTxt($index = 0){

        $data = [

            1 => '是',

            2 => '否'

        ];

        return $index ? $data[$index] : '';

    }

    private function reverseCheckTxt($str = ''){
        $str = trim($str);
        if(empty($str)){
            return 0;
        }
        $data = [
            '是' => 1,
            '否' => 2
        ];
        return $data[$str]; 
    }



    /**

     * 导出数据

     */

    public function export(){

        $keywords = input('keywords/s');

        $condition = [];

        if ($keywords){

            $condition['title'] = array('LIKE', $keywords.'%');

        }



        // 多语言

        $condition['lang'] = array('eq', $this->admin_lang);



        $list =  M('workorder')->where($condition)->order('id desc')->select();

        if (empty($list)){

            exit('暂无数据导出');

        }



        $title = [

            '序号', '供应商', '产品名称', '产品款式说明', '产品款式分类', '供应商地区',

            '产品尺寸', '包装尺寸', '包装重量', '价格', '运费', '材质', '可否单独销售',

            '单双包', '是否现货', '卖点，功能', '纸箱外观，合格证是否对接确认好', '是否出安装彩图',

            '送货方式', '代发发货方式', '结款方式', '是否送货上楼', '停产后是否清理厂家库存', '成品出图方式',

            '运营是否优先出图', '图片'

        ];

        $imgInTitleIndex = array_search("图片", $title);

        $data = [];

        foreach ($list as $key=>$val){

            $sizeArr = [$val['size_logn'], $val['size_width'], $val['size_height']];

            $pkArr = [$val['pk_long'], $val['pk_width'], $val['pk_height']];

            $imgs = explode(",", $val['img']);

            $data[] = [

                $key + 1,

                // $this->getUserGxsName($val['supplier_id']),

                $val['title'],

                $val['desc'],

                $val['cate'],

                $val['area'],

                implode('*', $sizeArr),

                implode('*', $pkArr),

                $val['weight'].' ',

                $val['price'].' ',

                $val['freight'],

                $val['material'],

                $this->checkTxt($val['is_sale']),

                $this->checkTxt($val['is_ds_packge']),

                $this->checkTxt($val['is_stock']),

                $val['fun_desc'],

                $val['appearance'] ? $this->appearanceData($val['appearance']) : '',

                $this->checkTxt($val['is_install_pic']),

                $val['delivery_method'],

                $val['df_method'],

                $val['settle_method'],

                $this->checkTxt($val['is_lou']),

                $this->checkTxt($val['is_clear_store']),

                $val['img_method'],

                $this->checkTxt($val['is_yy_img']),

                $imgs[0]

            ];

        }



        $filename = '采购记录_'.date('YmdHis').'.xlsx';



        import('phpexcel.PHPExcel', EXTEND_PATH);



        $objPHPExcel = new \PHPExcel();
       



        $objPHPExcel->getProperties();



        $sheet = $objPHPExcel->getActiveSheet();

        $titCol = 'A';

        foreach ($title as $key => $value) {

            // 单元格内容写入

            $sheet->setCellValue($titCol . '1', $value);

            $titCol++;

        }



        $column = 2;

        foreach ($data as $key => $rows) { // 行写入



            $span = ord("A");


            $sheet->getRowDimension($column)->setRowHeight(80);


            foreach ($rows as $keyName => $value) { // 列写入


                if($imgInTitleIndex != $keyName){
                    $sheet->setCellValue(chr($span) . $column, $value);
                }else{
                    $imgPath = $_SERVER['DOCUMENT_ROOT'].$value;
                    if(file_exists($imgPath)){               
                        // $objDrawing = new \PHPExcel_Worksheet_Drawing();         
                        // $objDrawing->setPath($imgPath);
                        // $objDrawing->setHeight(100);
                        // $objDrawing->setWidth(100); 
                        // $objDrawing->setCoordinates(chr($span) . $column);
                        // $objDrawing->setWorksheet($sheet);  
                        
                        $im_w = $im_h = 80;
                        $im = imagecreatetruecolor($im_w, $im_h);
                        $bg = imagecreatefromjpeg($imgPath);
                        list($bg_w, $bg_h) = getimagesize($imgPath);
                        imagecopyresampled($im, $bg, 0, 0, 0, 0, $im_w, $im_h, $bg_w, $bg_h); 
                        $objDrawing = new \PHPExcel_Worksheet_MemoryDrawing();
                        $objDrawing->setName('Sample image');
                        $objDrawing->setDescription('Sample image');
                        $objDrawing->setImageResource($im);
                        $objDrawing->setRenderingFunction(\PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG);
                        $objDrawing->setMimeType(\PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
                        $objDrawing->setHeight($im_h);
                        $objDrawing->setCoordinates(chr($span) . $column);
                        $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
                    }else{
                        //有图片名称，但是文件不存在   
                        $sheet->setCellValue(chr($span) . $column, $value);
                    }               
                }




                $span++;



            }



            $column++;

        }



        ob_end_clean();



        $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表



        //浏览器输出

        header('Content-Type: application/vnd.ms-execl;charset="UTF-8"');

        header('Content-Disposition: attachment;filename="'.$filename.'"');

        //header('Cache-Control: max-age=0');
      
header("Content-Transfer-Encoding: binary");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");  


        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

        $objWriter->save('php://output');

        exit();

    }

    public function import(){
        //error_reporting(E_ALL);
        $date = date('YmdHis');
        $tempFile = $_FILES['importFile']['tmp_name'];//获取缓存区图片,格式不能变
        $path = $_SERVER['DOCUMENT_ROOT']."/uploads/allimg/tmp_xls/". $date.'.xlsx'; //excel要被放置的位置
        move_uploaded_file($tempFile, $path);
     
        import('phpexcel.PHPExcel', EXTEND_PATH);
        $fileType = \PHPExcel_IOFactory::identify($path);  
        $reader = \PHPExcel_IOFactory::createReader($fileType);  

        $PHPExcel = $reader->load($path);
        $sheetCount = $PHPExcel->getSheetCount();
        $currentSheet = $PHPExcel->getSheet(0);
        $allColumn = ord($currentSheet->getHighestColumn()) - 65 + 1;
        $allRow = $currentSheet->getHighestRow();
        $excelArray = array();
        for($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
            for($currentColumn = 0; $currentColumn <= $allColumn - 1; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                if(is_object($val)){
                    $excelArray[$currentRow ][$currentColumn] = $val->__toString();
                }else{
                    $excelArray[$currentRow ][$currentColumn] = $val;    
                }
            }
        }
       

        $res = array('status' => 400, 'message'=>'');
        //读取图片
        $imageFilePath = $_SERVER['DOCUMENT_ROOT']."/uploads/allimg/".date('Ymd')."/"; //图片本地存储的路径
        if (!file_exists($imageFilePath)) { //如果目录不存在则递归创建
            mkdir($imageFilePath, 0777, true);
        }
        $tempFileData = array();
        $currentSheetImg = $currentSheet;
        foreach ($currentSheetImg->getDrawingCollection() as $k => $drawing) {
            $codata = $drawing->getCoordinates(); 
            $filename = $drawing->getIndexedFilename(); 
            ob_start();
            call_user_func(
                $drawing->getRenderingFunction(),
                $drawing->getImageResource()
            );
            $imageContents = ob_get_contents();
            $path = $imageFilePath. $codata.'_'.$filename; //excel要被放置的位置
            if(file_put_contents($path, $imageContents)){
                $tempFileData[$codata] = "/uploads/allimg/".date('Ymd')."/". $codata.'_'.$filename;
            }
            ob_end_clean();
        }


        if($excelArray){
            $mapping = $this->mappingRel();
            $mappingKeys = array_keys($mapping);
            $dataColumnMapping = array();
            $dataList = array();
            foreach($excelArray as $row =>$items){
                $tempData = array();
                $tempData['lang'] = 'cn';
                $tempData['admin_id'] = session('admin_id');
                $tempData['update_time'] = time();
                foreach($items as $col=> $val){
                    //根据表头设置， 如表头有变化，需要修改mappingRel 函数。
                    if($row == 1){
                        if($k = array_search($val, $mapping)){
                            if(!isset($dataColumnMapping[$val])){
                                $dataColumnMapping[$col] = $k;    
                            }
                        }elseif($val == '产品尺寸'){
                            $dataColumnMapping[$col] = 'product_size';
                        }elseif($val == '包装尺寸'){
                            $dataColumnMapping[$col] = 'package_size';
                        }
                    }else{
                        if($dataColumnMapping[$col] == 'product_size'){
                            $sizes = explode("*", $val);
                            $tempData['size_logn']    = $sizes[0];
                            $tempData['size_width']   = $sizes[1];
                            $tempData['size_height']  = $sizes[2];
                        }elseif($dataColumnMapping[$col] == 'package_size'){
                            $sizes = explode("*", $val);
                            $tempData['pk_long']    = $sizes[0];
                            $tempData['pk_width']   = $sizes[1];
                            $tempData['pk_height']  = $sizes[2];
                        }elseif($dataColumnMapping[$col] == 'img'){
                            $letterCol = chr( $col + 65);
                            if(isset($tempFileData[$letterCol.$row])){
                                $tempData['img']  = $tempFileData[$letterCol.$row];    
                            }else{
                                $tempData['img']  =  '';
                            }
                        }else{
                            if(!empty($val)){
                                //没字段的数据过滤掉，比如“序号”
                                if(empty($dataColumnMapping[$col])){
                                    continue;
                                }
                                //如果是字符并且只一个字的话
                                if(is_string($val) && strlen($val) == 3){
                                    $tempData[$dataColumnMapping[$col]] = $this->reverseCheckTxt($val);            
                                }else{
                                    $tempData[$dataColumnMapping[$col]] = $val;            
                                }                                
                            }                            
                        }                        
                    }                    
                }
                $dataList[] = $tempData;
                
            }
            //去除第一行表头空数据            
            array_shift($dataList);
            $workorder = M('workorder');

            // $dataList[] = array('name'=>'thinkphp','email'=>'thinkphp@gamil.com');
            // $dataList[] = array('name'=>'onethink','email'=>'onethink@gamil.com');
            if($insertResult = $workorder->insertAll($dataList)){
                $res['message'] = 'success';
                $res['status']  = 200;
            }
        }else{
            $res['message'] = 'no data';
        }
     
        echo json_encode($res);die;
    }

    //数据库字段英文与解释的关系
    public function mappingRel(){
        return array(
            "title"         => "产品名称",
            "supplier_id"   => "供应商",
            "desc"          => "产品款式说明",
            "img"           => "图片",
            "cate"          => "产品款式分类",
            "area"          => "供应商地区",
            "size_logn"     => "长度",
            "size_width"    => "宽度",
            "size_height"   => "高度",
            "pk_long"       => "包装长度",
            "pk_width"      => "包装宽度",
            "pk_height"     => "包装高度",
            "weight"        => "包装重量",
            "price"         => "价格",
            "freight"       => "运费",
            "material"      => "材质",
            "is_sale"       => "可否单独销售",
            "is_ds_packge"  => "单双包",
            "is_stock"      => "是否现货",
            "fun_desc"      => "卖点，功能",
            "appearance"    => "纸箱外观，合格证是否对接确认好",
            "is_install_pic"=> "是否出安装彩图",
            "delivery_method" => "送货方式",
            "df_method"     => "代发发货方式",
            "settle_method" => "结款方式",
            "is_lou"        => "是否送货上楼",
            "is_clear_store"=> "停产后是否清理厂家库存",
            "img_method"    => "成品出图方式",
            "is_yy_img"     => "运营是否优先出图"
        );
    }

/*    private function getUserGxsList(){

        $id = session('admin_id');

        if (empty($id)) return [];

        $username = M('admin')->where(array('admin_id' => $id))->getField('user_name');

        if (empty($username)) return [];

        

        $list = M('users_gxs')->where(array('wc_person' => $username))->field('id,gys_name')->select();

        return $list;

    }
*/
    

    // private function getUserGxsName($id){

    //     $name = M('users_gxs')->where(array('id'=>$id))->getField('gys_name');

    //     return $name;

    // }



}